/*
 * Neighbors.java 2011. 5. 30.
 *
 * Copyright 2011 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.naver.geotools;

import java.util.Comparator;
import java.util.List;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;

/**
 * @author kr12250
 */
public class Neighbors<T extends HasCoordinate> {
	public static final Comparator<Proximity<?>> ORDER_BY_DISTANCE = new Comparator<Proximity<?>>() {
		@Override
		public int compare(Proximity<?> a, Proximity<?> b) {
			return Double.compare(a.distance, b.distance);
		}
	};
	public List<Proximity<T>> proximities;

	public Neighbors(final Coordinate center, final int distanceInMeters, int limit, Iterable<T> things) {
		proximities = Ordering.from(ORDER_BY_DISTANCE).sortedCopy(Iterables.filter(Iterables.transform(things, new Function<T, Proximity<T>>() {
			@Override
			public Proximity<T> apply(T from) {
				return new Proximity<T>(center, from);
			}
		}), new Predicate<Proximity<T>>() {
			@Override
			public boolean apply(Proximity<T> input) {
				return input.distance < distanceInMeters;
			}
		}));
		if (proximities.size() > limit) {
			proximities = proximities.subList(0, limit);
		}
	}
}
